<?php
declare(strict_types=1);

namespace App\Helper;

use App\Constants\ErrorCode;

class RespHelper
{

    // 操作成功
    public const CODE_SUCCESS = ErrorCode::ERR_SUCCESS;
    // 操作失败
    public const CODE_FAIL = ErrorCode::ERR_REQUEST;
    // 权限不足
    public const CODE_FORBIDDEN = ErrorCode::ERR_FORBIDDEN;
    // 不存在
    public const CODE_NOTFOUND = ErrorCode::ERR_NOTFOUND;
    // 服务器内部错误
    public const CODE_ERROR = ErrorCode::ERR_SERVER;


    public const MESSAGE_SUCCESS = 'Success';
    public const MESSAGE_FAILURE = 'Failure. Please try again later';
    public const MESSAGE_ERROR = 'Server Internal Error ';
    public const MESSAGE_FORBIDDEN = 'Insufficient permissions';
    public const MESSAGE_NOTFOUND = 'Not exist or has been deleted';

    /**
     * 新增通用数据返回
     * @param int $code
     * @param string $message
     * @param mixed|null $data
     * @return array
     */
    public static function back(int $code = self::CODE_SUCCESS, string $message = self::MESSAGE_SUCCESS, mixed $data = null): array
    {
        return compact('code', 'message', 'data');
    }

    /**
     * 快速返回成功
     * @param string $msg
     * @param mixed|null $data
     * @return array
     */
    public static function success(mixed $data = null, string $msg = self::MESSAGE_SUCCESS): array
    {
        $code = static::CODE_SUCCESS;
        return static::back($code, $msg, $data);
    }

    /**
     * 快速返回失败
     * @param string $msg
     * @param mixed|null $data
     * @param int $code
     * @return array
     */
    public static function fail(string $msg = self::MESSAGE_FAILURE, mixed $data = null, int $code = self::CODE_FAIL): array
    {
        return static::back($code, $msg, $data);
    }

    /**
     * 快速返回错误
     * @param string $msg
     * @param mixed|null $data
     * @param int $code
     * @return array
     */
    public static function error(string $msg = self::MESSAGE_ERROR, mixed $data = null, int $code = self::CODE_ERROR): array
    {
        return static::back($code, $msg, $data);
    }

    /**
     * 权限不足
     * @param string $msg
     * @param mixed|null $data
     * @return array
     */
    public static function forbidden(string $msg = self::MESSAGE_FORBIDDEN, mixed $data = null): array
    {
        $code = static::CODE_FORBIDDEN;
        return static::back($code, $msg, $data);
    }

    /**
     * 数据不存在
     * @param string $msg
     * @param mixed|null $data
     * @return array
     */
    public static function notfound(string $msg = self::MESSAGE_NOTFOUND, mixed $data = null): array
    {
        $code = static::CODE_NOTFOUND;
        return static::back($code, $msg, $data);
    }

    /**
     * 判断是否是成功
     * @param array $resp
     * @return bool
     */
    public static function isSucceed(array $resp): bool
    {
        return @$resp['code'] === self::CODE_SUCCESS;
    }

}
